package com.eling.elcms.community.dao.hibernate;

import com.eling.elcms.community.dao.IOrganizationDao;
import com.eling.elcms.community.model.Organization;
import com.eling.elcms.core.dao.hibernate.GenericDaoHibernate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Repository
public class OrganizationDaoHibernate extends GenericDaoHibernate<Organization, Long> implements IOrganizationDao {

    public OrganizationDaoHibernate() {
        super(Organization.class);
    }
    
    public Organization add(@RequestBody Organization user) {
    	return this.save(user);
    }
    
    public void delete(@RequestBody Organization user) {
    	this.remove(user);
    }
    
    public Organization update(@RequestBody Organization user) {
    	return this.save(user);
    }
    
    public List<Organization> queryAll(@RequestBody Organization user) {
    	return this.getAll();
    }

    @SuppressWarnings("unchecked")
	@Override
	public String queryTheme(Long pkUser){
		String sql = "select c.theme from sm_user u,cm_orgcustomization c where u.pkOrganization=c.pkOrganization and  pkuser=:pkUser";
		List<String> theme=getSession().createNativeQuery(sql).setParameter("pkUser", pkUser).list();
		return !theme.isEmpty() && !StringUtils.isBlank(theme.get(0))?theme.get(0):"eling";
	}

    @Override
	public void insertOrganization(Organization organization) {
		String sql = "INSERT INTO cm_organization (pkOrganization, bankCardNumber, businessLicence, code, "+
				"	createTime, enableTime, introduction, name, status, version, count) VALUES "+
				"	(:pkOrganization, :bankCardNumber, :businessLicence, :code, :createTime, :enableTime, :introduction, :name, "+
				"	 'Setting',  '0', :count);";
		getSession().createNativeQuery(sql).setParameter("pkOrganization", organization.getPkOrganization())
				.setParameter("bankCardNumber", organization.getBankCardNumber())
				.setParameter("businessLicence", organization.getBusinessLicence())
				.setParameter("code", organization.getCode())
				.setParameter("count", organization.getCount())
				.setParameter("createTime", organization.getCreateTime())
				.setParameter("enableTime", organization.getEnableTime())
				.setParameter("introduction", organization.getIntroduction())
				.setParameter("name", organization.getName()).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean queryIsAllMenu(Long pkUser) {
		String sql = "select c.stopSvcPkgFilter from sm_user u,cm_orgcustomization c where u.pkOrganization=c.pkOrganization and  pkuser=:pkUser";
		List<Boolean> theme = getSession().createNativeQuery(sql).setParameter("pkUser", pkUser).list();
		return theme.isEmpty()?Boolean.FALSE:Boolean.valueOf(theme.get(0));
	}


}
